package com.gack.helper.shangshangqian;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 上上签公有云SDK测试
 */
public class BestsignClientTest {

    //开发者ID
//    private static String developerId = "2013493662570250784";
    private static String developerId = "2022849088998867561";
    //开发者私钥
//    private static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJWFcAVHnqFkDYWzwT0K7FsiDObJ469j7OWV4GsJkvl7UnPp6IhKCN0StImKTNR2wLcEWPqJmfwCjI6De61Mi+CxFBA/Akdz9/VVOxzI2OmrEmgr0etEApGCCT4LUzVzHDYXvXcw3uypJgxNH4mZO1VrVn54eB/hhyocTB2adVjcALa9+oK5UiDLY9+f8KRX8lPZYwFSAjHuLE6jYWpGCzuJ1CUpLTu04sWj3QSmoKU6bmHQdEr0lDa5tVQ4ujV2gI1hvyDopxlPsUvV0P+LmSTdSlXWIC+kVfK02FhKzazJpihkr0U3tKAJYst42Hnyr78Po2MC7FjIhe+dhWTW4tAgMBAAECggEAPLQkz+qGb+YiBv5cEU380Tgns9TiIqFPpRhurHpFWnmtAYl1vFUSOVwny1BcFrbolC2tMQ+NxsPBwvqQFy2RBB4UJC4/Z36lO/xUn5MPReYtQh4qxHVank8hpvp8XBK/1eEyQUmC8PXruIWFYGFQnaeTSjdU9yl9WL0TH7K5eOAi+cRZZA3X34lw8IdzzlkmEd1Ju2hQJtOKlM3MwepEHIuIycre6Ug+QWqzJsjg4M4euzIldCoghskFrsMLhni6D+qeBtZ41AY3r+qnkr3aGAhBJHncjc/HLsuTd1vUMjSgddHlitZ/9btPZ7yQQFdBWm7e2SiWgHt3hZBoF4ejaQKBgQDkMIRmn0YdYMpUhMjW7kgqW6KJqoQXoEwUvBosR5OniQSheYuAej8mc9CdDJsU5b4C9gj4sN00y/99hxAf232WmILcNZ+njQ64ld+avQ9DyRMvOjb5ZFf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yW9+K+FVyHXG7hJK9gpp0m9gaI+OEJCYqIVC/KUgQGAH71R2RiTJZgkJ1KzDgBsswMUrtg2Z0QDfl6XANrQJBAN4BBq29iWyUFOGsTuyab9h0gxh/lVurrznRCw/OvhMQYmVHASpMC5SeNEBdZGh2U2w8qQXqp7ZNsff1YTkJUjsCQQCUrzWHzPtYSw36GPX/+cPqI/qNWWnOV//8oVV8VCuYfHYZvNjEb9Lgt4Tx5O0lJeT/3wKmns/uM6hSW5bIx143AkAZbEKoiMkA/yA5C7NqEvF19znAB3RCMDH7y/2ZTNKlej3aXTw77MNyvH89U7SY5dv9zCCLBek4zkLwI1CD6JZbAkBV/j/nmxaDqmUbEPS2Z6537PcsaVpYjWzwoB7hGY1dVB66JA77DfHZJkst3EmMAq6/jivqUk/QZPAlMfOzjBthAkEAiTWgY8Fzg74BwkO5hd/PS5LWCyY3kG1ssusbaEt7GuLsX1oCZ7G+azajISCT+kx9B1QeSrD7v91mGsZDp7Lb1w==";


    //公有云Server的完整HOST，需要根据不同的环境配置
    /**
     * 测试环境（http）：http://openapi.bestsign.info/openapi/v2
     * 测试环境（https）：https://openapi.bestsign.info/openapi/v2
     * 正式环境（https）：https://openapi.bestsign.cn/openapi/v2
     */
    private static String serverHost = "https://openapi.bestsign.cn/openapi/v2";

    //已封装的HTTP接口调用的的client，您可以使用它来调用常规api和特殊api，您可以在此BestsignOpenApiClient中添加新的接口方法方便调用。
    private static BestsignOpenApiClient openApiClient = new BestsignOpenApiClient(developerId, privateKey, serverHost);

    public static void main(String[] args) throws Exception{

//        personalUserReg(); //个人用户注册       POST方法示例
        
//        downloadContract("1234567890"); //下载合同pdf文件  GET方法示例
        
        String verify = openApiClient.verify("", "");
        System.err.println(verify);
        String verify_enterprise = openApiClient.verifyEnterprise("杭州旺丹网络科技有限公司", "500100199011210012", 
        		"张鑫宇", "232302199606013215");
        System.err.println("verifyEnterprise:::"+verify_enterprise);
    }
    
    public static String personalAuthentication(String name,String identify){
    	String verify = null;
		try {
			verify = openApiClient.verify(name, identify);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("个人认证验证异常");
		}
    	return verify;
    }
    
    public static String enterpriseCertification(String name, String identity, String legalPerson,
			String legalPersonIdentity) {
    	String verify = null;
		try {
			verify = openApiClient.verifyEnterprise(name, identity, legalPerson, legalPersonIdentity);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("企业认证验证异常");
		}
    	return verify;
    }
    
    public static String enterpriseCertificationThreePoint(String name, String identity, String legalPerson) {
    	String verify = null;
		try {
			verify = openApiClient.verifyEnterpriseThreePoint(name, identity, legalPerson);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("企业认证验证异常");
		}
    	return verify;
    }
    
    /**
     * 个人用户注册
     * [注册，设置实名信息，申请数字证书，生成默认签名]
     * @throws Exception
     */
    public static void personalUserReg() throws Exception{
        //用户注册
        String account = "18910001001"; //账号
        String name = "尚尚"; //用户名称
        String mail = ""; //用户邮箱
        String mobile = "18910001001"; //用户手机号码

        //设置个人实名信息
        String identity = "110101199301018270"; //证件号码
        String identityType = "0"; //证件类型  0-身份证
        String contactMail = ""; //联系邮箱
        String contactMobile = mobile; //联系电话
        String province = "浙江"; //所在省份
        String city = "杭州"; //所在城市
        String address = "西湖区万塘路317号华星世纪大楼102"; //联系地址
       
        //注册返回异步申请证书任务id
        String taskId = openApiClient.userPersonalReg(account, name, mail, mobile, identity, identityType, contactMail, contactMobile, province, city, address);
        //查询任务状态
        System.out.println("account="+account+" taskId:"+taskId);
        
    }
    
    /**
     * 下载合同
     * @throws Exception
     */
    public static void downloadContract(String contractId) throws Exception{
        byte[] pdf = openApiClient.contractDownload(contractId);
        byte2File(pdf, "D:\\test", contractId+".pdf"); //文件下载到本地目录
        System.out.println("download contract pdf path=" + "D:\\test\\" + contractId+".pdf");
    }

    /**
     * 辅助方法，本地文件转为byte[]
     * @param filePath
     * @return
     */
    private static byte[] inputStream2ByteArray(String filePath) {
        byte[] data = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(filePath);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            data = out.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (Exception e) {
                //ignore
            }
        }
        return data;
    }

    /**
     * 辅助方法，byte数组保存为本地文件
     * @param buf
     * @param filePath
     * @param fileName
     */
    private static void byte2File(byte[] buf, String filePath, String fileName)
    {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try
        {
            File dir = new File(filePath);
            if (!dir.exists())
            {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
